package com.heima.wemedia.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.stream.StreamUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.WemediaConstants;
import com.heima.common.dtos.PageResponseResult;
import com.heima.common.dtos.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.CustomException;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.utils.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 姜星宇
 * @date 2024/8/27 15:50
 */
@Slf4j
@Service
@Transactional
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Resource
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Resource
    private WmMaterialMapper wmMaterialMapper;


    @Override
    public ResponseResult<List<WmNews>> findAll(WmNewsPageReqDto dto) {
        //1.检查参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.分页参数检查
        dto.checkParam();
        //3.获取当前登录人的信息
        WmUser user = WmThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
            //4.分页条件查询
            Page<WmNews> page = new Page<>(dto.getPage(), dto.getSize());
            LambdaQueryWrapper<WmNews> wrapper = Wrappers.<WmNews>lambdaQuery()
                    .eq(ObjectUtil.isNotEmpty(dto.getStatus()), WmNews::getStatus, dto.getStatus())     //状态精确查询
                    .eq(ObjectUtil.isNotEmpty(dto.getChannelId()), WmNews::getChannelId, dto.getChannelId())    //频道精确查询
                    .between(ObjectUtil.isAllNotEmpty(dto.getBeginPubDate(), dto.getBeginPubDate()), WmNews::getPublishTime, dto.getBeginPubDate(), dto.getEndPubDate())  //时间范围查询
                    .like(ObjectUtil.isAllNotEmpty(dto.getKeyword()), WmNews::getTitle, dto.getKeyword())  //关键字模糊查询
                    .eq(WmNews::getUserId, user.getId())   //查询当前登录用户的文章
                    .orderByDesc(WmNews::getCreatedTime);  //发布时间倒序查询

            //5.分页查询
            page(page, wrapper);
            //6.结果返回
            return PageResponseResult.<List<WmNews>>builder()
                    .size(dto.getSize())
                    .currentPage(dto.getPage())
                    .total(dto.getPage())
                    .size(Convert.toInt(page.getTotal()))
                    .data(page.getRecords())
                    .build();

        }

    @Override
    public ResponseResult<Object>   submitNews(WmNewsDto dto) {
        //1.条件判断
        if(ObjectUtil.isEmpty(dto.getContent())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.保存或修改文章
        WmNews wmNews = BeanUtil.toBean(dto, WmNews.class);
        //3.封面图片 List -->string
        if(CollUtil.isNotEmpty(dto.getImages())){
            //[1dddfsd.jpg,sdlfjldk.jpg]-->   1dddfsd.jpg,sdlfjldk.jpg
            String join = StrUtil.join(",", dto.getImages());
            wmNews.setImages(join);
        }
        //4.如果当前封面类型为自动-1
        if(ObjectUtil.equal(dto.getType(), WemediaConstants.WM_NEWS_TYPE_AUTO)){
            wmNews.setType(null);
        }
        //5.保存或更新数据
        saveOrUpdateWmNews(wmNews);
        //6.判断是否为草稿 如果为草稿结束当前方法
        if(ObjectUtil.equal(dto.getStatus(),WmNews.Status.NORMAL.getCode())){
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        //7.不是草稿，保存文章内容图片与素材的关系
        //获取到文章内容中图片信息
       List<String> materials = extractUrlInfo(dto.getContent());
        saveRelativeInfoForContent(materials,wmNews.getId());
        //8.不是草稿，保存文章封面图片与素材的关系，如果当前布局是自动，需要匹配封面图片
        saveRelativeInfoForCover(dto,wmNews,materials);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

    }

    @Override
    public ResponseResult<Object> getdelNews(Integer id) {
        if (ObjectUtil.isEmpty(id)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = this.getById(id);
        if (wmNews == null || wmNews.getId() == null || !wmNews.getId().equals(id)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        if (wmNews.getStatus() == 9) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (this.removeById(id)) {
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        } else {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

    }

    @Override
    public ResponseResult<Object> downOrUp(WmNewsDto wmNewsDto) {
        if(BeanUtil.isEmpty(wmNewsDto) || wmNewsDto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = this.getById(wmNewsDto.getId());
        if(BeanUtil.isEmpty(wmNews) || wmNews.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        if(wmNews.getStatus() != 9) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        wmNews.setId(wmNewsDto.getId());
        wmNews.setStatus(wmNewsDto.getEnable());
        if(this.updateById(wmNews)){
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }else{
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
    }


    /**
     * 第一个功能：如果当前封面类型为自动，则设置封面类型的数据
     * 匹配规则：
     * 1，如果内容图片大于等于1，小于3  单图  type 1
     * 2，如果内容图片大于等于3  多图  type 3
     * 3，如果内容没有图片，无图  type 0
     * <p>
     * 第二个功能：保存封面图片与素材的关系
     */
    private void saveRelativeInfoForCover(WmNewsDto dto, WmNews wmNews, List<String> materials) {
        List<String> images = dto.getImages();
        //如果当时封面类型为自动，则设置封面类型的数据
        if(ObjectUtil.equal(dto.getType(),WemediaConstants.WM_NEWS_TYPE_AUTO)){
            if(CollUtil.isEmpty(materials)){
                //无图
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
            }else if(CollUtil.size(materials)>=3){
                //多图
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                images=CollUtil.sub(materials,0,3);
            }else {
                //单图
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                images=CollUtil.sub(materials,0,1);
            }
            //修改文章
            if(CollUtil.isNotEmpty(images)){
                wmNews.setImages(StrUtil.join(",",images));
            }
            super.updateById(wmNews);
        }
        if(CollUtil.isNotEmpty(images)){
            saveRelativeInfo(images,wmNews.getId(),WemediaConstants.WM_COVER_REFERENCE);
        }
    }


    /**
     * 处理文章内容图片与素材的关系
     */
    private void saveRelativeInfoForContent(List<String> materials, Integer newsId) {
        saveRelativeInfo(materials,newsId,WemediaConstants.WM_COVER_REFERENCE);
    }


    /**
     * 保存文章图片与素材的关系到数据库中
     * @param materials
     * @param newsId
     * @param type
     */

    private void saveRelativeInfo(List<String> materials, Integer newsId, Short type) {
        if(CollUtil.isEmpty(materials)){
            return;
        }
        //通过图片的url查询素材中的id
        List<WmMaterial> dbMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, materials));
        //判断素材是否有效
        if(CollUtil.isEmpty(dbMaterials)){
            //手动抛出异常
            //第一个功能：能够提示调用者素材失效了，
            //第二个功能，进行数据的回滚
            throw new CustomException(AppHttpCodeEnum.MATERIASL_REFERENCE_FAIL);
        }

        if(materials.size() != dbMaterials.size()){
            throw new CustomException(AppHttpCodeEnum.MATERIASL_REFERENCE_FAIL);
        }

        List<Integer> idList = CollStreamUtil.toList(dbMaterials,WmMaterial::getId);
        //批量保存
        wmNewsMaterialMapper.saveRelations(idList,newsId,type);



    }


    /**
     * 提取文章内容中的图片信息
     * @param content
     * @return
     */

    private List<String> extractUrlInfo(String content) {
        return StreamUtil.of(JSONUtil.toList(content, JSONObject.class))
                .filter(jsonObject -> StrUtil.equals(jsonObject.getStr("type"),"image"))
                .map(jsonObject -> jsonObject.getStr("value"))
                .collect(Collectors.toList());
    }

    /**
     * 保存或修改文章
     * @param wmNews
     */
    private void saveOrUpdateWmNews(WmNews wmNews) {
        if(ObjectUtil.isEmpty(wmNews.getId())){
            //补全属性
            wmNews.setUserId(WmThreadLocalUtil.getUser().getId());
            wmNews.setCreatedTime(new Date());
            wmNews.setSubmitedTime(new Date());
            wmNews.setEnable((short) 1);//默认上架
            //保存
            super.save(wmNews);
        }
        //删除文章图片与素材关系
        LambdaQueryWrapper<WmNewsMaterial> queryWrapper = Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,wmNews.getId());
        this.wmNewsMaterialMapper.delete(queryWrapper);
        //修改数据
        super.updateById(wmNews);
    }

}
